package com.huluobo.a2111douyindemo.home;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.huluobo.a2111douyindemo.R;
import com.huluobo.a2111douyindemo.adapter.CommonPagerAdapter;
import com.huluobo.a2111douyindemo.databinding.FragmentHomeBinding;
import com.huluobo.a2111douyindemo.home.tabItem.CommonFragment;
import com.huluobo.a2111douyindemo.home.tabItem.TabEntity;
import com.huluobo.mvvm_base.mvvm.base.view.BaseFragment;

import java.util.ArrayList;
import java.util.List;

public class HomeFragment extends BaseFragment<FragmentHomeBinding> {
    //tab标签的集合
    private ArrayList<CustomTabEntity> tabs = new ArrayList<>();
    //fragment的集合
    private List<Fragment> fragments = new ArrayList<>();

    //page的adapter
    private CommonPagerAdapter commonPagerAdapter;


    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home;
    }

    @Override
    protected void initData() {
        tabs.clear();
        fragments.clear();

        tabs.add(new TabEntity("推荐", 0, 0));
        tabs.add(new TabEntity("同城", 0, 0));
        tabs.add(new TabEntity("关注", 0, 0));

        dataBinding.homeMainTab.setTabData(tabs);

        //fragment需要和tab的数量保持一致
        for (int i = 0; i < tabs.size(); i++) {
            fragments.add(new CommonFragment());
        }

        commonPagerAdapter = new CommonPagerAdapter(requireActivity(), fragments);
        dataBinding.homeVp2.setAdapter(commonPagerAdapter);

        //设置vp2的缓存大小
//        dataBinding.homeVp2.setOffscreenPageLimit(1);

    }

    @Override
    protected void initView() {
        dataBinding.homeVp2.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                //vp2和tab联动
                dataBinding.homeMainTab.setCurrentTab(position);
            }
        });
        dataBinding.homeMainTab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                //tab和vp2联动
                dataBinding.homeVp2.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
    }
}